package org.summer.lawyer.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.summer.common.core.exception.ServiceException;
import org.summer.common.core.utils.MapstructUtils;
import org.summer.common.mybatis.core.page.PageQuery;
import org.summer.common.mybatis.core.page.TableDataInfo;
import org.summer.lawyer.constant.SystemConstants;
import org.summer.lawyer.constant.enums.PaymentMethod;
import org.summer.lawyer.domain.PayChannel;
import org.summer.lawyer.domain.bo.paychannel.PayChannelBo;
import org.summer.lawyer.domain.vo.payapp.PayAppVo;
import org.summer.lawyer.domain.vo.paychannel.PayChannelVo;
import org.summer.lawyer.mapper.PayChannelMapper;
import org.summer.lawyer.pay.client.PayClient;
import org.summer.lawyer.pay.client.PayClientFactory;
import org.summer.lawyer.service.IPayAppService;
import org.summer.lawyer.service.IPayChannelService;

import java.time.Duration;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static org.summer.lawyer.util.CacheUtils.buildAsyncReloadingCache;

/**
 * 支付通道Service业务层处理
 *
 * @author summer
 * @date 2024-06-21
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PayChannelServiceImpl extends ServiceImpl<PayChannelMapper, PayChannel>  implements IPayChannelService {

    private final IPayAppService payAppService;

    private final PayClientFactory payClientFactory;

    @Getter
    private final LoadingCache<Long, PayClient> clientCache = buildAsyncReloadingCache(Duration.ofSeconds(10L),
            new CacheLoader<Long, PayClient>(){
                @Override
                public PayClient load(Long channelId)  {
                    //查询，然后尝试清空
                    PayChannelVo channelVo = baseMapper.selectVoById(channelId);
                    if(ObjectUtil.isNotNull(channelVo)){
                        payClientFactory.createOrUpdatePayClient(channelVo);
                    }
                    return payClientFactory.getPayClient(channelId);
                }
            });

    /**
     *
     */
//    @PostConstruct
//    public void init(){
//
//    }

    /**
     * 查询支付通道
     *
     * @param id 主键
     * @return 支付通道
     */
    @Override
    public PayChannelVo selectPayChannelVoById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public PayChannelVo selectPayChannelVoByCode(String code, String wxAppId) {
        LambdaQueryWrapper<PayChannel> lqw = Wrappers.lambdaQuery();
        lqw.eq(PayChannel::getWxAppId,wxAppId);
        lqw.eq(PayChannel::getChannelCode, code);
        return baseMapper.selectVoOne(lqw, false);
    }

    /**
     * 分页查询支付通道列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 支付通道分页列表
     */
    @Override
    public TableDataInfo<PayChannelVo> selectPageList(PayChannelBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PayChannel> lqw = buildQueryWrapper(bo);
        Page<PayChannelVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的支付通道列表
     *
     * @param bo 查询条件
     * @return 支付通道列表
     */
    @Override
    public List<PayChannelVo> selectPayChannelVoList(PayChannelBo bo) {
        LambdaQueryWrapper<PayChannel> lqw = Wrappers.lambdaQuery();
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PayChannel> buildQueryWrapper(PayChannelBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PayChannel> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getAppId() != null, PayChannel::getAppId, bo.getAppId());
        lqw.eq(StrUtil.isNotBlank(bo.getStatus()), PayChannel::getStatus, bo.getStatus());
        lqw.eq(bo.getFeeRate() != null, PayChannel::getFeeRate, bo.getFeeRate());
        lqw.eq(StrUtil.isNotBlank(bo.getMchNo()), PayChannel::getMchNo, bo.getMchNo());
        lqw.like(StrUtil.isNotBlank(bo.getMchName()), PayChannel::getMchName, bo.getMchName());
        lqw.eq(StrUtil.isNotBlank(bo.getWxAppId()), PayChannel::getWxAppId, bo.getWxAppId());
       // lqw.eq(StrUtil.isNotBlank(bo.getAppSecret()), PayChannel::getAppSecret, bo.getAppSecret());
        lqw.eq(bo.getPayLimit() != null, PayChannel::getPayLimit, bo.getPayLimit());
        lqw.eq(StrUtil.isNotBlank(bo.getApiKeyTwo()), PayChannel::getApiKeyTwo, bo.getApiKeyTwo());
        lqw.eq(StrUtil.isNotBlank(bo.getApiKeyThree()), PayChannel::getApiKeyThree, bo.getApiKeyThree());
       // lqw.eq(StrUtil.isNotBlank(bo.getCert()), PayChannel::getCert, bo.getCert());
        return lqw;
    }

    /**
     * 新增支付通道
     *
     * @param bo 支付通道
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(PayChannelBo bo) {
        PayChannel add = MapstructUtils.convert(bo, PayChannel.class);
        validEntityBeforeSave(add);
        PayAppVo payAppVo = payAppService.selectPayAppVoById(bo.getAppId());
        if(ObjectUtil.isNull(payAppVo)){
            throw new ServiceException("请添加支付配置");
        }
        add.setMchNo(payAppVo.getMchNo());
        add.setMchName(payAppVo.getMchName());
        add.setStatus(SystemConstants.ACTIVE);
        add.setFeeRate(0);
        add.setPayLimit(9999999999L);
        add.setChannelCode(PaymentMethod.WECHAT_MINIAPP.getCode());
        add.setApiVersion("v3");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        //创建支付缓存
        PayChannelVo channelVo = baseMapper.selectVoById(add.getId());
        payClientFactory.createOrUpdatePayClient(channelVo);
        return flag;
    }

    /**
     * 修改支付通道
     *
     * @param bo 支付通道
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(PayChannelBo bo) {
        PayChannel update = MapstructUtils.convert(bo, PayChannel.class);
        validEntityBeforeSave(update);
        PayAppVo payAppVo = payAppService.selectPayAppVoById(bo.getAppId());
        if(ObjectUtil.isNull(payAppVo)){
            throw new ServiceException("请添加支付配置");
        }
        update.setMchNo(payAppVo.getMchNo());
        update.setMchName(payAppVo.getMchName());
        //更新支付缓存
        //创建支付缓存
        PayChannelVo channelVo = baseMapper.selectVoById(update.getId());
        payClientFactory.createOrUpdatePayClient(channelVo);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public void changePayChannelStatus(PayChannelBo bo) {
        LambdaUpdateWrapper<PayChannel> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(PayChannel::getId, bo.getId())
                .set(PayChannel::getStatus, bo.getStatus());
        baseMapper.update(updateWrapper);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PayChannel entity){
        PayChannelBo bo = new PayChannelBo();
        bo.setAppId(entity.getAppId());
        bo.setWxAppId(entity.getWxAppId());
        bo.setId(entity.getId());
        if(checkUniqueAppId(bo)){
            throw new ServiceException(StrUtil.format("“{}”已经存在，请勿重复设置", entity.getWxAppId()));
        }
    }

    /**
     * 校验并批量删除支付通道信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean checkUniqueAppId(PayChannelBo bo) {
        return baseMapper.exists(new LambdaQueryWrapper<PayChannel>().eq(PayChannel::getAppId,bo.getAppId()).eq(PayChannel::getWxAppId, bo.getWxAppId()).ne(bo.getId() != null,PayChannel::getId, bo.getId()));
    }


    @Override
    public PayClient getPayClient(Long channelId) {
        return clientCache.getUnchecked(channelId);
    }
}
